<template>
  <div class="px-5 py-4 bg-white" v-loading="loading">
    <el-row :gutter="0">
      <el-col :span="24" :xs="24">
        <!-- 标题 -->
        <HeadTitle text="患者登记查询"/>
      </el-col>
      <el-col :span="24" :xs="24">
        <!-- 搜索 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="" prop="keyWord">
            <el-input v-model="queryParams.keyWord" placeholder="证件号/名字" clearable style="width: 240px"/>
          </el-form-item>
          <el-form-item label="开单时间" style="width: 308px">
            <el-date-picker v-model="dateRange" @change="getList" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                            start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item label="就诊状态" prop="visitStatus">
            <el-select v-model="queryParams.visitStatus" @change="getList" placeholder="全部" clearable style="width: 240px">
              <el-option label="就诊中" value="0"/>
              <el-option label="就诊结束" value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getList">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row :gutter="20" justify="space-between">
      <el-col :span="20">
        <el-button type="primary" icon="plus"
                   @click="; (open = true), reset()">新增
        </el-button>
        <el-button type="primark" plain :disabled="batchDisabled" @click="handleCommand('batchDc')">
          <svg aria-hidden="true" class="mr-1 w-4 h-5">
            <use xlink:href="#icon-notDC"></use>
          </svg>
          解绑
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-row :gutter="0" class="mt-4">
      <el-col :span="24">
        <Table :column="tableColumn" :table-data="userList" :option="option" @current-change="handleCurrentChange"
               @size-change="handleSizeChange" @command="handleCommand" @selection-change="handleSelectionChange">
          <template #status="{ row }">
            <span v-if="row.visitStatus == '0'" style="color: #00a991; font-weight: bold;">就诊中</span>
            <span v-else style="color: #86909c">已结束</span>
          </template>
          <template #historyBtn="{ row }">
            <span title="开单记录" style="cursor: pointer;">
              <svg aria-hidden="true" class="ml-4 w-4 h-4" @click="getHistory(row)">
                <use xlink:href="#icon-searchId"/>
              </svg>
            </span>
          </template>
          <template #unbindBtn="{ row }">
            <span title="解绑" style="cursor: pointer;">
              <svg aria-hidden="true" class="ml-4 w-4 h-4" v-if="row.visitStatus == '0'" @click="handleDc(row)">
                <use xlink:href="#icon-notDC"/>
              </svg>
              <svg aria-hidden="true" class="ml-4 w-4 h-4" v-else>
                <use xlink:href="#icon-DC"/>
              </svg>
            </span>
          </template>
          <template #editBtn="{ row }">
            <span title="修改" style="cursor: pointer;">
              <svg aria-hidden="true" class="ml-4 w-4 h-4" @click="handleCommand('edit', row)">
                <use xlink:href="#icon-edit"/>
              </svg>
            </span>
          </template>
          <template #delBtn="{ row }">
            <span title="删除" style="cursor: pointer;">
              <svg aria-hidden="true" class="ml-4 w-4 h-4" v-if="row.visitStatus != '0'" @click="handleDel(row)">
                <use xlink:href="#icon-delete"/>
              </svg>
              <!--
              <svg aria-hidden="true" class="ml-4 w-4 h-4" v-else>
                <use xlink:href="#icon-delete-grey"/>
              </svg>
              -->
            </span>
          </template>
          <template #bindBtn="{ row }">
            <span v-if="row.visitStatus == '0'" title="一键续绑" style="cursor: pointer;">
              <svg @click="bind(row)" aria-hidden="true" class="ml-4 w-4 h-4">
                <use xlink:href="#icon-calBpActive"/>
              </svg>
            </span>
          </template>
        </Table>
      </el-col>
    </el-row>

    <!-- 添加或者修改患者对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body width="720px" @open="getEqList" :close-on-click-modal="false">
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="identityNumber">
              <el-input v-model="form.identityNumber" placeholder="请输入身份证号" @keyup="fmtInfo">
                <template #append>
                  <svg aria-hidden="true" class="w-4 h-4" @click="handleSearchId">
                    <use xlink:href="#icon-searchId"/>
                  </svg>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="patientName">
              <el-input v-model="form.patientName" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="form.gender" class="ml-4">
                <el-radio label="1" size="large">男</el-radio>
                <el-radio label="2" size="large">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
                              format="YYYY/MM/DD" style="width: 270px" @change="editAge"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" placeholder="请输入年龄"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="就诊地" prop="place">
              <el-select v-model="form.place" placeholder="请选择就诊地" @change="placeChange" style="width: 270px">
                <el-option label="在家" value="在家"/>
                <el-option label="在院" value="在院"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="床位号" prop="bedNo">
              <el-input v-model="form.bedNo" maxlength="20" :disabled="form.place != '在院'"
                        placeholder="请输入床位号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疾病诊断" prop="diagnosis">
              <el-input v-model="form.diagnosis" placeholder="请输入疾病诊断"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="家庭地址">
              <el-cascader :options="regionData" filterable v-model="codeArray" @change="handleChange" clearable
                           style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="">
              <el-input v-model="form.address" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="flex justify-between">
          <h1 class="text-lg mb-5">设备管理</h1>
        </div>
        <el-row>
          <el-col :span="10">
            <el-form-item label="设备编号" prop="equipmentNo">
              <el-select v-model="form.equipmentNo" filterable placeholder="请选择" :disabled="form.visitStatus == '1'">
                <el-option v-for="item in EqOptins" :key="item.equipmentId" :label="item.equipmentNo" :value="item.equipmentNo"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(deptRef)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="visitHistoryDialog" :title="historyDialogTitle" :close-on-click-modal="false">
      <el-row style="margin-bottom: 20px;">
        <el-form :model="queryHistory" :inline="true">
          <el-date-picker v-model="historyDateRange" value-format="YYYY-MM-DD" type="daterange"
                          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                          :disabled-date="disabledDate" @calendar-change="handleDateRangeChange"
                          @focus="handleFocus" @change="reqHistoryData" :clearable="false"/>
        </el-form>
      </el-row>

      <el-table ref="visitHistoryTableRef" :data="visitHistoryData" v-loading="historyDataLoading"
                @selection-change="handleVisitHistorySelection" size="small" style="width: 100%" height="400">
        <el-table-column prop="visitNoStr" type="selection" :selectable="historyDataSelectable" width="50"/>
        <el-table-column prop="visitNoStr" label="序列号" align="center"/>
        <el-table-column prop="visitTime" label="就诊时间" align="center"/>
        <el-table-column prop="rentalDays" label="绑定时长" align="center"/>
        <el-table-column prop="bedNo" label="床号" align="center"/>
        <el-table-column prop="visitStatus" label="备注" align="center">
          <template #default="scope">
            <span v-if="scope.row.useStatus !== '1'" style="color: #E6A23C;">监测数据未达标！</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-popover :visible="visiblePopover" placement="top" :width="240">
            <el-checkbox-group v-model="printCheckList">
              <el-checkbox label="heart">脉率</el-checkbox>
              <el-checkbox label="spo2">血氧</el-checkbox>
              <el-checkbox label="temp">体温</el-checkbox>
            </el-checkbox-group>
            <el-divider style="margin: 8px 0;" />
            <div style="text-align: right;">
              <el-button size="small" text @click="visiblePopover = false">取消</el-button>
              <el-button @click="mergePrint" type="primary" size="small" :disabled="printCheckList.length <= 0">确定</el-button>
            </div>

            <template #reference>
              <el-button @click="visiblePopover = true" :disabled="printVisitIds.length <= 0" type="primary">合并打印</el-button>
            </template>
          </el-popover>
          <el-button @click="visitHistoryDialog = false;visiblePopover = false;">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus'
import {reactive, ref, toRefs} from 'vue'
import {regionData, CodeToText, TextToCode} from 'element-china-area-data'
import {
  addREG,
  batchDc,
  getVisitHistoryData,
  DC,
  delReg,
  eqList,
  getPatInfo,
  listReg,
  searchId,
  updateReg,
  continueBind,
} from '@/api/patientREG'
import {formatTime, getCurrentAgeByBirthDate, getDay} from '@/utils'
import {getAgeByIdCard, getBirthdayByIdCard, getSexByIdCard} from '@/utils/identityNumber'
import {useRouter} from "vue-router";
const loading = ref(false)

const queryRef = ref()
const dateRange = ref([]) //时间
const title = ref('新增患者') //标题
const open = ref(false)
const codeArray: any = ref([]) //城市code
const EqOptins: any = ref([]) //设备号
const batchDisabled = ref(true)
const ids: any = ref([])

/**表单 */
interface FromType {
  visitNo?: NumUn | string //就诊id
  identityNumber: StrUn //身份证号
  patientName: StrUn //姓名
  gender: StrUn //性别
  birthday: StrUn //出生日期
  age: NumUn //年龄
  phone: NumUn //电话
  place: StrUn //就诊地
  bedNo: StrUn //床位号
  diagnosis?: StrUn //诊断
  province: StrUn
  city: StrUn
  district: StrUn
  address: StrUn //详细地址
  equipmentId: StrUn //设备ID
  equipmentNo: StrUn //设备编号
  dataType: StrUn //数据类型

  readonly visitStatus?: StrUn
  readonly visitNoStr?: StrUn
}

/**列表查询 */
interface QueryType {
  pageNum: number
  pageSize: number
  keyWord?: string //证件号和姓名
  startTime?: string //开始时间
  endTime?: string //结束时间
  visitStatus?: string //就诊状态
}

interface DataType {
  form: FromType
  queryParams: QueryType
  rules: Recordable
}

const data = reactive<DataType>({
  form: {
    patientName: undefined,
    gender: '1',
    identityNumber: undefined,
    birthday: undefined,
    age: undefined,
    phone: undefined,
    place: '在院',
    bedNo: undefined, //床位号
    diagnosis: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    address: undefined,
    equipmentId: undefined,
    equipmentNo: undefined,
    dataType: 'TJ02',
    visitStatus: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    identityNumber: [
      {required: true, message: '身份证号不能为空', trigger: 'blur'},
      {
        required: true,
        pattern: /^[1-9][0-9]{5}(18|19|20)[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}([0-9]|(X|x))/,
        message: '请输入正确身份证号',
        trigger: 'blur'
      }
    ],
    patientName: [{required: true, message: '患者姓名不能为空', trigger: 'blur'}],
    birthday: [{required: true, message: '出生日期不能为空', trigger: 'blur'}],
    age: [
      {required: true, message: '年龄不能为空', trigger: 'blur'},
      {required: true, pattern: /^[0-9]+$/, message: '请输入正确年龄', trigger: 'blur'}
    ],
    phone: [
      {
        required: false,
        pattern: /^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    place: [{required: true, message: '就诊地不能为空', trigger: 'blur'}],
    equipmentNo: [{required: true, message: '设备编号不能为空', trigger: 'blur'}],
    bedNo: [{required: true, message: '床位号不能为空', trigger: 'blur'}],
  }
})

const {queryParams, form, rules} = toRefs(data)
const mySelectable = (row) => { // 禁用某一行
  return row.visitStatus === "0";
}
//表格配置
const tableColumn = [
  {type: 'selection', selectable: mySelectable},
  {type: 'index', label: '序号', align: 'center', width: '60'},
  {prop: 'patientName', label: '用户名称', align: 'center', width: '120'},
  {prop: 'deptName', label: '科室', align: 'center', width: '100'},
  {prop: 'bedNo', label: '床位号', align: 'center'},
  {prop: 'identityNumber', label: '证件号', align: 'center'},
  {prop: 'visitNoStr', label: '序列号', align: 'center'},
  {prop: 'visitStatus', label: '就诊状态', align: 'center', slot: 'status', width: '100'},
  {prop: 'visitTime', label: '就诊时间', align: 'center', showOverflowTooltip: true},
  {
    label: '操作',
    align: 'center',
    buttons: [
      {slot: 'historyBtn'},
      {slot: 'unbindBtn'},
      {slot: 'editBtn'},
      {slot: 'delBtn'},
      {slot: 'bindBtn'},
    ]
  }
] as Table.Column[]

interface State {
  userList: Array<object>
  option: Table.Option
}

const state = reactive<State>({
  userList: [
    {
      userId: '123',
      status: '123',
      createTime: '123'
    }
  ],
  option: {
    loading: false,
    showPagination: true,
    height: 630,
    paginationConfig: {
      currentPage: 1,
      pageSize: 10,
      total: 0
    },
    rowStyle: function (obj) {
      let visitTimeStr = obj.row.visitTime;
      if (visitTimeStr) {
        var tempStrs = visitTimeStr.split(" ");
        var timeStrs = tempStrs[1].split(":");
        let hour = timeStrs[0];
        if (obj.row.visitStatus == '0' && (hour === '09' || hour === '10')) {
          return {
            background: "#f0f9eb"
          };
        }
      }
    }
  }
})
const {userList, option} = toRefs(state)

/** 患者列表 */
const getList = () => {
  option.value.loading = true
  if (dateRange.value?.length) {
    queryParams.value.startTime = dateRange.value[0] //开始时间
    queryParams.value.endTime = dateRange.value[1] //结束时间
  } else {
    queryParams.value.startTime = ""
    queryParams.value.endTime = ""
  }
  listReg(queryParams.value).then((res: any) => {
    userList.value = res.rows
    if (option.value.paginationConfig) {
      option.value.paginationConfig.total = res.total
    }
    option.value.loading = false
  })
}

/** 重置按钮操作 */
const resetQuery = (queryRef: { resetFields: () => void }) => {
  queryRef.resetFields()
  dateRange.value = []
  queryParams.value.startTime = '' //开始时间
  queryParams.value.endTime = '' //结束时间
  getList()
}

/** 身份证搜索 */
const handleSearchId = () => {
  let identityNumber = form.value.identityNumber;
  if (!identityNumber) {
    ElMessage.warning('请先输入身份证号码！');
    return;
  }
  searchId({identityNumber: identityNumber}).then((res: any) => {
    const {data} = res
    if(!data.identityNumber) {
      ElMessage.warning('未找到患者信息！');
      return ;
    }
    Object.assign(form.value, data)
    if (data.province) {
      codeArray.value = [
        TextToCode[data.province].code,
        TextToCode[data.province][data.city].code,
        TextToCode[data.province][data.city][data.district].code
      ]
    }
    if (data.birthday) {
      form.value.age = getAge(formatTime(data.birthday, 'yyyy-MM-dd'));
    }
  })
}
const getAge = (strAge) => {
  const birArr = strAge.split("-");
  const birYear = Number(birArr[0]);
  const birMonth = Number(birArr[1]);
  const birDay = Number(birArr[2]);

  const today = new Date();
  const nowYear = today.getFullYear();
  const nowMonth = today.getMonth() + 1; //记得加1
  const nowDay = today.getDate();
  let returnAge;

  if (birArr === null) {
    return 0
  }
  const d = new Date(birYear, birMonth - 1, birDay);

  if (d.getFullYear() === birYear && (d.getMonth() + 1) === birMonth && d.getDate() === birDay) {
    if (nowYear === birYear) {
      returnAge = 0; //
    } else {
      let ageDiff = nowYear - birYear;
      if (ageDiff > 0) {
        if (nowMonth === birMonth) {
          let dayDiff = nowDay - birDay;
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          let monthDiff = nowMonth - birMonth;
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
      } else {
        //返回-1 表示出生日期输入错误 晚于今天
        return 0;
      }
    }
    return returnAge;
  } else {
    // 日期格式错误
    return 0;
  }
}

/** 编辑取消按钮 */
const cancel = (): void => {
  open.value = false
  reset()
}

/** 表单重置 */
const reset = (): void => {
  form.value = {
    patientName: undefined,
    gender: '1',
    identityNumber: undefined,
    birthday: undefined,
    age: undefined,
    phone: undefined,
    place: '在院',
    bedNo: undefined, //床位号
    diagnosis: undefined, //慢性病
    province: undefined,
    city: undefined,
    district: undefined,
    address: undefined,
    equipmentId: undefined,
    equipmentNo: undefined,
    dataType: 'TJ02',
    visitStatus: undefined,
  }
  codeArray.value = []
}

/** 提交按钮 */
const deptRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(form.value.equipmentNo) {
        let output = EqOptins.value.find((obj : any) => obj.equipmentNo === form.value.equipmentNo);
        if(output && output.equipmentId) {
          form.value.equipmentId = output.equipmentId;
        }
      }
      loading.value = true;
      if (form.value.visitNo != undefined) {
        form.value.visitNo = form.value?.visitNoStr
        updateReg(form.value).then(() => {
          loading.value = false
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addREG(form.value).then(() => {
          loading.value = false
          open.value = false
          getList()
          ElMessage.success('新增成功')
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

/** 城市选择 */
const handleChange = () => {
  switch (codeArray.value?.length) {
    case 1:
      form.value.province = CodeToText[codeArray.value[0]]
      break
    case 2:
      form.value.province = CodeToText[codeArray.value[0]]
      form.value.city = CodeToText[codeArray.value[1]]
      break
    case 3:
      form.value.province = CodeToText[codeArray.value[0]]
      form.value.city = CodeToText[codeArray.value[1]]
      form.value.district = CodeToText[codeArray.value[2]]
      break
    default:
      form.value.province = undefined
      form.value.city = undefined
      form.value.district = undefined
      break
  }
}

const placeChange = (value) => {
  if(value === "在院") {
    rules.value.bedNo = [{required: true, message: '床位号不能为空', trigger: 'blur'}];
  }
  if(value === "在家") {
    rules.value.bedNo = [];
    form.value.bedNo = "";
  }
}

/** 操作按钮 */
const handleCommand = (command: string | number, row?: any) => {
  if (command == 'edit') {
    //修改
    getPatInfo({visitNo: row.visitNoStr as string}).then((res: any) => {
      const data = JSON.parse(JSON.stringify(res.data))
      form.value = data
      //城市转换
      if (data.province) {
        codeArray.value = [
          TextToCode[data.province].code,
          TextToCode[data.province][data.city].code,
          TextToCode[data.province][data.city][data.district].code
        ]
      }
      open.value = true
      title.value = "修改患者"
    })
  } else if (command === 'batchDc') {
    ElMessageBox.confirm('您确定要解绑所选患者吗？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        batchDc({visitNos: ids.value.join(",")}).then(() => {
          getList()
          ElMessage.success('解绑成功！')
        })
      })
      .catch(() => {
      })
  }
}

/** 解绑*/
const handleDc = (row: { patientName: string; visitNoStr: string }) => {
  ElMessageBox.confirm('你确定要将' + row.patientName + '解绑吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      DC({visitNo: row.visitNoStr}).then(() => {
        getList()
        ElMessage.success('解绑成功！')
      })
    })
    .catch(() => {
    })
}

/**
 * 删除
 * @param row
 */
const handleDel = (row: { patientName: string; visitNoStr: string }) => {
  ElMessageBox.confirm(`是否确认删除${row.patientName}？`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delReg({visitNo: row.visitNoStr as string}).then(() => {
        getList()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {
    })
}

//填充年龄
const editAge = () => {
  if (form.value.birthday) {
    form.value.age = getCurrentAgeByBirthDate(form.value.birthday)
  } else {
    form.value.age = undefined
  }
}
/** 分页*/
const handleCurrentChange = (pageNum: number) => {
  if (option.value.paginationConfig) {
    option.value.paginationConfig.currentPage = pageNum
    queryParams.value.pageNum = pageNum
  }
  getList()
}

/** 分页*/
const handleSizeChange = (pageSize: number) => {
  if (option.value.paginationConfig) {
    option.value.paginationConfig.pageSize = pageSize
    queryParams.value.pageSize = pageSize
  }
  getList()
}

/**
 * 获取设备列表
 */
const getEqList = () => {
  let data = {
    equipmentType: 'TJ02',
  };
  eqList(data).then((res: any) => {
    EqOptins.value = res.data
  })
}

getList()

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = []
  selection.forEach((val) => {
    ids.value.push(val.visitNoStr)
  })
  batchDisabled.value = !ids.value.length;
}

const fmtInfo = () => {
  let id: string = form.value.identityNumber || "";
  let reg = /^[1-9][0-9]{5}(18|19|20)[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}([0-9]|(X|x))/;
  if (reg.test(id)) {
    let birthdayByIdCard = getBirthdayByIdCard(id);
    if (birthdayByIdCard) {
      form.value.birthday = birthdayByIdCard;
    }
    let sexByIdCard = getSexByIdCard(id);
    if (sexByIdCard) {
      form.value.gender = sexByIdCard;
    }
    let ageByIdCard = getAgeByIdCard(id);
    if (ageByIdCard) {
      form.value.age = ageByIdCard;
    }
  }
}

/** 开单记录 相关代码 */
const getHistory = (row: { patientName: string; patientIdStr: string; identityNumber: string }) => {
  historyDialogTitle.value = "患者(" + row.patientName + ")开单记录";
  queryHistory.value.patientId = row.patientIdStr;
  historyDateRange.value = [getBeforeDay(4), getDay()]
  visitHistoryDialog.value = true;
  reqHistoryData()
}

const visitHistoryDialog = ref(false)
const historyDialogTitle = ref('')
const historyDataLoading = ref(false)
const historyDateRange = ref([])
const historyState = reactive({
  visitHistoryData: [],
  queryHistory: {
    patientId: '',
    startTime: '',
    endTime: '',
    dataType: 'TJ02',
  }
})
const {visitHistoryData, queryHistory} = toRefs(historyState)
/** 获取列表 */
const reqHistoryData = () => {
  historyDataLoading.value = true;

  if (historyDateRange.value?.length) {
    queryHistory.value.startTime = historyDateRange.value[0] //开始时间
    queryHistory.value.endTime = historyDateRange.value[1] //结束时间
  }

  getVisitHistoryData(queryHistory.value).then((res: any) => {
    historyDataLoading.value = false;
    visitHistoryData.value = res.data;
  })
}

// 限制监测数据未达标的不能被打印
const historyDataSelectable = (row) => row.useStatus === "1";

const getBeforeDay = (days: number) => {
  let now = new Date();
  let date2 = new Date(now.getTime());
  date2.setDate(now.getDate() - days);
  return formatTime(date2, 'yyyy-MM-dd');
}

// 多选的开单信息
const printVisitIds: any = ref([])
const handleVisitHistorySelection = (selection: any) => {
  printVisitIds.value = []
  selection.forEach((val) => {
    printVisitIds.value.push(val.visitNoStr)
  });
}

// ------------ 限制日期查询范围只能选五天 开始
const pickDay = ref()
const handleFocus = () => {
  pickDay.value = null
}
const limitTime = 1000 * 60 * 60 * 24 * 4
const disabledDate = (time: Date) => {
  if (pickDay.value) {
    return (
      time.getTime() < pickDay.value.getTime() - limitTime ||
      time.getTime() > pickDay.value.getTime() + limitTime ||
      time.getTime() > Date.now()
    )
  } else {
    return time.getTime() > Date.now()
  }
}
const handleDateRangeChange = (val: Date[]) => {
  const [pointDay] = val
  pickDay.value = pointDay
}
// ------------ 限制日期查询范围只能选五天 结束

const printCheckList = ref(['temp', 'spo2', 'heart']);
const visiblePopover = ref(false);
const router = useRouter();
const mergePrint = () => {
  if (printVisitIds.value.length > 0) {
    localStorage.setItem("dy", JSON.stringify(printCheckList.value));
    localStorage.setItem("visitNos", JSON.stringify(printVisitIds.value));
    localStorage.setItem("isMerge", "true");
    router.push({
      name: 'PrintPage',
    });
    visiblePopover.value = false;
  } else {
    ElMessage.error('请选择要打印的记录！');
  }
}

// 患者一键续绑
const bind = (row: { patientName: string; visitNoStr: string }) => {
  ElMessageBox.confirm(`是否确认续绑患者${row.patientName}？`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true;
    continueBind({visitNo: row.visitNoStr as string}).then((res:any) => {
      loading.value = false;
      getList();
      ElMessage.success(res.msg);
    });
  }).catch(() => {
  })
}
</script>
<style scoped lang="less">
.dialog-footer button:first-child {
  margin-right: 10px;
}

.addEq {
  width: 82px;
  height: 26px;
  line-height: 24px;
  border-radius: 4px;
  background: #e8fff8;
  box-sizing: border-box;
  border: 1px solid #00a991;
  text-align: center;
  color: #00a991;
  cursor: pointer;
}
</style>
<style>
.el-input__wrapper {
  width: 100%;
}

.calBp > .el-dialog__body {
  padding: 10px;
}

.el-input-number.is-without-controls .el-input__wrapper {
  padding: 1px 11px;
}

.el-input-number .el-input__inner {
  text-align: left;
}
</style>
